<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <i class="fas fa-arrow-left" @click="goBack"></i>
      <p>确认订单</p>
      <div style="width: 24px;"></div>
    </header>

    <!-- 商家信息 -->
    <div class="business-info">
      <div class="business-header">
        <i class="fas fa-store"></i>
        <span>{{ business.businessName }}</span>
      </div>
      <div class="delivery-info">
        <i class="fas fa-clock"></i>
        <span>预计{{ business.deliveryTime || '30' }}分钟送达</span>
      </div>
    </div>

    <!-- 配送地址 -->
    <div class="address-section" @click="selectAddress">
      <div class="address-header">
        <i class="fas fa-map-marker-alt"></i>
        <span>配送地址</span>
      </div>
      <div class="address-content" v-if="selectedAddress">
        <div class="address-details">
          <span class="contact-name">{{ selectedAddress.contactName }}</span>
          <span class="contact-gender">{{ selectedAddress.contactSex === 1 ? '先生' : '女士' }}</span>
          <span class="contact-phone">{{ formatPhone(selectedAddress.contactTel) }}</span>
        </div>
        <div class="address-full">{{ selectedAddress.address }}</div>
      </div>
      <div class="address-empty" v-else>
        <span>请选择配送地址</span>
      </div>
      <i class="fas fa-chevron-right"></i>
    </div>

    <!-- 订单商品列表 -->
    <div class="order-items">
      <h3>订单详情</h3>
      <div class="items-list">
        <div v-for="(item, index) in orderItems" :key="index" class="order-item">
          <div class="item-info">
            <span class="item-name">{{ item.food.foodName }}</span>
            <span class="item-price">¥{{ formatPrice(item.food.foodPrice) }}</span>
          </div>
          <div class="item-quantity">×{{ item.quantity }}</div>
        </div>
      </div>
    </div>

    <!-- 价格明细 -->
    <div class="price-details">
      <div class="price-row">
        <span>商品金额</span>
        <span>¥{{ formatPrice(subtotal) }}</span>
      </div>
      <div class="price-row">
        <span>配送费</span>
        <span>¥{{ formatPrice(business.deliveryPrice || 0) }}</span>
      </div>
      <div class="price-row total">
        <span>实付金额</span>
        <span>¥{{ formatPrice(totalAmount) }}</span>
      </div>
    </div>

    <!-- 备注信息 -->
    <div class="remark-section">
      <textarea v-model="remark" placeholder="请输入备注信息（可选）" maxlength="100"></textarea>
    </div>

    <!-- 提交订单 -->
    <div class="submit-section">
      <div class="total-amount">
        <span class="amount-label">合计：</span>
        <span class="amount-value">¥{{ formatPrice(totalAmount) }}</span>
      </div>
      <button class="submit-btn" @click="submitOrder" :disabled="!selectedAddress || submitting">
        {{ submitting ? '提交中...' : '提交订单' }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { businessAPI } from '@/api/business.js';
import { cartAPI } from '@/api/cart.js';
import { orderAPI } from '@/api/order.js';
import { addressAPI } from '@/api/address.js';

const route = useRoute();
const router = useRouter();

const businessId = ref(route.query.businessId);
const business = ref({
  businessName: '',
  deliveryPrice: 0,
  deliveryTime: '30',
  startPrice: 0
});
const orderItems = ref([]); // 从购物车筛选出的当前商家商品
const selectedAddress = ref(null);
const remark = ref('');
const submitting = ref(false);

// 页面加载时获取数据
onMounted(async () => {
  await loadBusinessInfo();
  await loadCartItems();
  await loadAddresses();
  loadSelectedAddress();
});

// 加载商家信息
const loadBusinessInfo = async () => {
  try {
    const response = await businessAPI.getBusiness(businessId.value);
    if (response.data && response.data.success === true && response.data.data) {
      business.value = response.data.data;
    } else if (response.data) {
      business.value = response.data;
    }
  } catch (error) {
    console.error('获取商家信息失败:', error);
  }
};

// 加载购物车商品并筛选当前商家的商品
const loadCartItems = async () => {
  try {
    const response = await cartAPI.getCartItems();
    let cartData = [];

    if (response.data && response.data.success === true && response.data.data) {
      cartData = response.data.data;
    } else if (response.data) {
      cartData = response.data;
    }

    console.log('所有购物车商品:', cartData);
    console.log('当前商家ID:', businessId.value);

    // 筛选当前商家的商品 - 加强数据验证
    orderItems.value = cartData.filter(item => {
      if (!item || !item.business || !item.food) return false;

      // 确保比较的是相同类型
      const itemBusinessId = parseInt(item.business.id);
      const currentBusinessId = parseInt(businessId.value);

      const isCurrentBusiness = itemBusinessId === currentBusinessId;
      console.log(`商品 ${item.food.foodName || '未知'} 商家ID: ${itemBusinessId}, 当前商家ID: ${currentBusinessId}, 匹配: ${isCurrentBusiness}`);
      return isCurrentBusiness;
    });

    console.log('筛选后的订单商品:', orderItems.value);

    if (orderItems.value.length === 0) {
      alert('购物车中没有该商家的商品，将返回商家页面');
      router.back();
      return;
    }

    // 验证商品数据完整性
    orderItems.value.forEach(item => {
      if (!item.food.foodName) {
        item.food.foodName = '商品信息加载失败';
      }
      if (!item.food.foodPrice) {
        item.food.foodPrice = 0;
      }
    });

  } catch (error) {
    console.error('获取购物车商品失败:', error);
    alert('获取购物车商品失败');
  }
};

// 加载地址列表
const loadAddresses = async () => {
  try {
    const response = await addressAPI.getUserAddresses();
    let addresses = [];

    if (response.data && response.data.success === true && response.data.data) {
      addresses = response.data.data;
    } else if (response.data) {
      addresses = response.data;
    }

    // 如果有地址，默认选择第一个
    if (addresses.length > 0 && !selectedAddress.value) {
      selectedAddress.value = addresses[0];
    }
  } catch (error) {
    console.error('获取地址列表失败:', error);
  }
};

// 从sessionStorage加载选中的地址
const loadSelectedAddress = () => {
  const savedAddress = sessionStorage.getItem('selectedAddress');
  if (savedAddress) {
    selectedAddress.value = JSON.parse(savedAddress);
    sessionStorage.removeItem('selectedAddress'); // 清除已使用的地址
  }
};

// 计算属性
const subtotal = computed(() => {
  return orderItems.value.reduce((sum, item) => sum + (item.food.foodPrice || 0) * item.quantity, 0);
});

const totalAmount = computed(() => {
  return subtotal.value + (business.value.deliveryPrice || 0);
});

// 格式化价格
const formatPrice = (price) => {
  if (price === null || price === undefined) return '0.00';
  return parseFloat(price).toFixed(2);
};

// 格式化手机号显示
const formatPhone = (phone) => {
  if (!phone) return '';
  return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3');
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 选择地址
const selectAddress = () => {
  router.push({
    path: '/userAddress',
    query: {
      from: 'order',
      businessId: businessId.value
    }
  });
};

// 提交订单
const submitOrder = async () => {
  if (!selectedAddress.value) {
    alert('请选择配送地址');
    return;
  }

  if (orderItems.value.length === 0) {
    alert('购物车为空，无法下单');
    return;
  }

  // 检查是否达到起送价
  if (totalAmount.value < business.value.startPrice) {
    alert(`未达到起送价¥${business.value.startPrice}`);
    return;
  }

  submitting.value = true;

  try {
    // 修复订单数据结构 - 根据后端要求调整
    const orderData = {
      business: {
        id: parseInt(businessId.value)
      },
      deliveryAddress: {
        id: parseInt(selectedAddress.value.id)
      },
      remark: remark.value,
      orderTotal: parseFloat(totalAmount.value)
    };

    console.log('提交订单数据:', orderData);

    const response = await orderAPI.addOrders(orderData);

    if (response.data && response.data.success) {
      // 订单创建成功，跳转到支付页面
      const orderId = response.data.data?.id;
      if (orderId) {
        router.push({
          path: '/payment',
          query: { orderId }
        });
      } else {
        // 如果没有返回订单ID，跳转到订单列表
        router.push('/orderList');
      }
    } else {
      alert('订单创建失败：' + (response.data?.message || '未知错误'));
    }
  } catch (error) {
    console.error('提交订单失败:', error);
    alert('提交订单失败，请重试');
  } finally {
    submitting.value = false;
  }
};
</script>

<style scoped>
.wrapper {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  padding-bottom: 14vw;
}

/* Header样式 */
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 4vw;
  box-sizing: border-box;
}

.wrapper header i {
  font-size: 5vw;
  cursor: pointer;
}

.wrapper header p {
  margin: 0;
  font-weight: bold;
}

/* 商家信息 */
.business-info {
  background: white;
  padding: 4vw;
  margin-top: 12vw;
  border-bottom: 1px solid #f0f0f0;
}

.business-header {
  display: flex;
  align-items: center;
  margin-bottom: 2vw;
}

.business-header i {
  color: #0097ff;
  margin-right: 2vw;
  font-size: 4.5vw;
}

.business-header span {
  font-size: 4.2vw;
  font-weight: bold;
  color: #333;
}

.delivery-info {
  display: flex;
  align-items: center;
  font-size: 3.5vw;
  color: #666;
}

.delivery-info i {
  margin-right: 2vw;
  color: #0097ff;
  font-size: 3.8vw;
}

/* 配送地址 */
.address-section {
  background: white;
  padding: 4vw;
  margin-top: 2vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 2vw;
}

.address-header i {
  color: #0097ff;
  margin-right: 2vw;
  font-size: 4.5vw;
}

.address-header span {
  font-size: 4vw;
  font-weight: bold;
  color: #333;
}

.address-content {
  flex: 1;
}

.address-details {
  margin-bottom: 1vw;
}

.contact-name {
  font-size: 4vw;
  font-weight: bold;
  color: #333;
  margin-right: 2vw;
}

.contact-gender {
  font-size: 3.5vw;
  color: #666;
  margin-right: 3vw;
}

.contact-phone {
  font-size: 3.5vw;
  color: #666;
}

.address-full {
  font-size: 3.5vw;
  color: #333;
  line-height: 1.4;
}

.address-empty {
  flex: 1;
  font-size: 4vw;
  color: #999;
  text-align: center;
  padding: 3vw 0;
}

.address-section i.fa-chevron-right {
  color: #ccc;
  font-size: 4vw;
}

/* 订单商品列表 */
.order-items {
  background: white;
  margin-top: 2vw;
  padding: 4vw;
}

.order-items h3 {
  font-size: 4.2vw;
  color: #333;
  margin: 0 0 3vw 0;
  padding-bottom: 2vw;
  border-bottom: 1px solid #f0f0f0;
}

.items-list {
  max-height: 40vw;
  overflow-y: auto;
}

.order-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 2.5vw 0;
  border-bottom: 1px solid #f5f5f5;
}

.order-item:last-child {
  border-bottom: none;
}

.item-info {
  display: flex;
  justify-content: space-between;
  flex: 1;
  margin-right: 3vw;
}

.item-name {
  font-size: 3.8vw;
  color: #333;
}

.item-price {
  font-size: 3.8vw;
  color: #ff4757;
  font-weight: bold;
}

.item-quantity {
  font-size: 3.5vw;
  color: #666;
  min-width: 8vw;
  text-align: right;
}

/* 价格明细 */
.price-details {
  background: white;
  margin-top: 2vw;
  padding: 4vw;
}

.price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 2vw 0;
  font-size: 3.8vw;
  color: #666;
}

.price-row.total {
  border-top: 1px solid #f0f0f0;
  margin-top: 2vw;
  padding-top: 3vw;
  font-size: 4.2vw;
  font-weight: bold;
  color: #333;
}

/* 备注信息 */
.remark-section {
  background: white;
  margin-top: 2vw;
  padding: 4vw;
}

.remark-section textarea {
  width: 100%;
  border: 1px solid #e0e0e0;
  border-radius: 1vw;
  padding: 3vw;
  font-size: 3.8vw;
  resize: none;
  box-sizing: border-box;
  min-height: 20vw;
}

.remark-section textarea:focus {
  outline: none;
  border-color: #0097ff;
}

/* 提交订单 */
.submit-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 2vw 4vw;
  border-top: 1px solid #f0f0f0;
  z-index: 1000;
}

.total-amount {
  display: flex;
  align-items: center;
}

.amount-label {
  font-size: 3.8vw;
  color: #666;
}

.amount-value {
  font-size: 4.5vw;
  color: #ff4757;
  font-weight: bold;
}

.submit-btn {
  background: #0097ff;
  color: white;
  border: none;
  border-radius: 2vw;
  padding: 3vw 6vw;
  font-size: 4vw;
  font-weight: bold;
  cursor: pointer;
  min-width: 25vw;
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.submit-btn:not(:disabled):hover {
  background: #0077cc;
}
</style>